import { fileIo as fs, ReadOptions, WriteOptions } from '@kit.CoreFileKit';
import { AsyncCallback } from '@ohos.base';
import { util } from '@kit.ArkTS';

export class blackholeSink implements fs.Stream{
  close(): Promise<void>;

  close(callback: AsyncCallback<void, void>): void;

  close(callback?: unknown): void | Promise<void> {
    if (callback) {
      (callback as AsyncCallback<void, void>)(undefined, undefined);
      return;
    }
    return Promise.resolve();
  }

  closeSync(): void {}

  flush(): Promise<void>;

  flush(callback: AsyncCallback<void, void>): void;

  flush(callback?: unknown): void | Promise<void> {
    if (callback) {
      (callback as AsyncCallback<void, void>)(undefined, undefined);
      return;
    }
    return Promise.resolve();
  }

  flushSync(): void {}

  write(buffer: string | ArrayBuffer, options?: WriteOptions | undefined): Promise<number>;

  write(buffer: string | ArrayBuffer, callback: AsyncCallback<number, void>): void;

  write(buffer: string | ArrayBuffer, options: WriteOptions, callback: AsyncCallback<number, void>): void;

  write(buffer: unknown, options?: unknown, callback?: unknown): void | Promise<number> {
    // 计算“写入”的字节数
    const bytesWritten = typeof buffer === 'string'
      ? new util.TextEncoder().encodeInto(buffer).length
      : (buffer as ArrayBuffer).byteLength;

    // 处理 callback 风格
    if (typeof options === 'function') {
      const cb = options as AsyncCallback<number, void>;
      cb(undefined, bytesWritten); // 成功回调
      return;
    }
    if (typeof callback === 'function') {
      callback(undefined, bytesWritten);
      return;
    }

    // 返回 Promise
    return Promise.resolve(bytesWritten);
  }

  writeSync(buffer: string | ArrayBuffer, options?: WriteOptions | undefined): number {
    return typeof buffer === 'string'
      ? new util.TextEncoder().encodeInto(buffer).length
      : buffer.byteLength;
  }

  read(buffer: ArrayBuffer, options?: ReadOptions | undefined): Promise<number>;

  read(buffer: ArrayBuffer, callback: AsyncCallback<number, void>): void;

  read(buffer: ArrayBuffer, options: ReadOptions, callback: AsyncCallback<number, void>): void;

  read(buffer: unknown, options?: unknown, callback?: unknown): void | Promise<number> {
    const cb = (typeof options === 'function' ? options : callback) as AsyncCallback<number, void> | undefined;
    if (cb) {
      cb(undefined, 0);
      return;
    }
    return Promise.resolve(0);
  }

  readSync(buffer: ArrayBuffer, options?: ReadOptions | undefined): number {
    return 0;
  }
}